package common;

import io.github.bonigarcia.wdm.WebDriverManager;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.edge.EdgeOptions;
import org.openqa.selenium.support.ui.WebDriverWait;

import java.io.*;
import java.text.SimpleDateFormat;
import java.time.Duration;

public class Utils {
    public static WebDriver driver = null;
    public static WebDriver secondDriver = null;

    public WebDriverWait wait = null;
    public WebDriverWait secondWait = null;

    public static String initScore = "";

    public Utils(String url){
        //调用driver对象
        driver = createDriver();
        wait = new WebDriverWait(driver, Duration.ofSeconds(5));
        driver.get(url);
    }

    //获取驱动对象
    private WebDriver createDriver() {
        if (driver == null){
            //下载驱动
            WebDriverManager.edgedriver().setup();
            EdgeOptions options = new EdgeOptions();
            //允许访问所有链接
            options.addArguments("--remote-allow-origins=*");

            driver = new EdgeDriver(options);
            //隐式等待
            driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(5));
        }
        return driver;
    }

    //模拟第二个玩家
    public WebDriver createSecondDriver(){
        if (secondDriver == null){
            // 创建新的EdgeOptions实例
            EdgeOptions options = new EdgeOptions();
            options.addArguments("--remote-allow-origins=*");

            // 创建第二个WebDriver实例
            secondDriver = new EdgeDriver(options);
            secondDriver.manage().timeouts().implicitlyWait(Duration.ofSeconds(5));

            secondWait = new WebDriverWait(secondDriver, Duration.ofSeconds(5));
        }
        return secondDriver;
    }

    //屏幕截图
    public void ScreenShot(String str) throws IOException {
        //屏幕截图文件目录
        //   ./src/test/java/images/
        //                         /2025-03-02/
        //                                    /test01_09372010.png
        //                                    /test02_09372011.png
        //                         /2025-03-03/
        //                                    /test01_19372010.png
        //                                    /test02_19372011.png

        SimpleDateFormat sim1 = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat sim2 = new SimpleDateFormat("HHmmssSS");

        String dirTime = sim1.format(System.currentTimeMillis());
        String fileTime = sim2.format(System.currentTimeMillis());

        //./src/test/java/images/2025-03-02/test01_13972011.png
        String fileName = "./src/test/java/images"+ dirTime + "/" + str + "_" + fileTime + ".png";

        File srcFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
        FileUtils.copyFile(srcFile,new File(fileName));
    }

}

